<?php

namespace app\admin\controller;

use app\admin\model\Link as ModelLink;
use app\index\validate\Link as ValidateLink;
use think\exception\ValidateException;

class Link extends Base
{
    public function index()
    {
        return view();
    }
    public function examineAll()
    {
        $res = ModelLink::where('status', 0)->update(['status' => 1]);
        if ($res) return success();
        return error();
    }
    public function list()
    {
        $param = input();
        $web_name = @$param['web_name'];
        if (empty($web_name)) {
            $list = ModelLink::order('status asc ,sort asc')->paginate($param['limit']);
        } else {
            $list = ModelLink::where('web_name', 'like', '%' . $web_name . '%')->order('status asc ,sort asc')->paginate($param);
        }
        return success($list, '操作成功', 0);
    }
    public function update()
    {
        if (request()->isPost()) {
            $param = input();
            $res = ModelLink::update($param);
            if ($res) return success();
            else return error();
        }
    }
    public function add()
    {
        if (request()->isPost()) {
            $param = input();
            $param['status'] = isset($param['status']) ? 1 : 0;
            $hasTag = ModelLink::where('web_name', $param['web_name'])->findOrEmpty()->isEmpty();
            if (!$hasTag) return error('已存在该网页名称');
            try {
                Validate(ValidateLink::class)->check($param);
                $res = ModelLink::create($param);
                if ($res) return success();
            } catch (ValidateException $e) {
                return error($e->getError());
            }
            return error();
        }
    }
    public function del($id)
    {
        $id = input('id');
        $idArr = explode(',', $id);
        $res = ModelLink::whereIn('id', $idArr)->delete();
        if ($res) return success();
        else return error();
    }
}
